package top.kent90.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.util.JSONPObject;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.dubbo.common.json.JSON;
import org.apache.dubbo.common.json.JSONObject;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import top.kent90.common.controller.BaseController;
import top.kent90.common.object.LoginObject;
import top.kent90.common.util.DateUtil;
import top.kent90.common.util.FastDFSClient;
import top.kent90.common.util.LoadProperties;
import top.kent90.pojo.Item;
import top.kent90.pojo.ItemInfo;
import top.kent90.pojo.ZczyAuditItem;
import top.kent90.pojo.ZczyUser;
import top.kent90.service.ItemInfoService;
import top.kent90.service.ItemService;
import top.kent90.service.RedisService;
import top.kent90.service.ZczyAuditItemService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.Reader;
import java.text.ParseException;
import java.util.*;

/**
 * 项目控制器
 *  1.展示类项目
 *  2.交易类项目
 *  3.已成功项目
 *  4.发起众筹项目（添加）
 */

@Controller
@RequestMapping("item")
public class ItemController extends BaseController {

    //json与字符串互转
    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    @Reference
    ItemService itemService;

    @Reference
    ItemInfoService itemInfoService;

    @Reference
    RedisService redisService;

    @Reference
    ZczyAuditItemService zczyAuditItemService;


    /**
     * 展示类项目首页
     * @return
     */
    @RequestMapping("showItem")
    public String showItem( String count, String limit, HttpServletRequest request){
        System.out.println("-------准备跳转到\"展示项目\"页面--------");
        //把前端传过来的分页信息入参
        Map<String,Object> map=new HashMap<>();
        map.put("count",count);
        map.put("limit",limit);
        //查询项目信息
        List<Item> itemList=itemService.queryItemByPages(map);
        if (itemList!=null){
            //测试redis
            /*boolean isLset = redisService.lSet("redisList", itemList);
            System.out.println(isLset);
            List<Object> redisList = redisService.lGet("redisList", 0, -1);
            System.out.println("redisList:"+redisList.toString());*/
            //计算剩余时间
            for (Item item:itemList){
                try {
                    //使用org.apache.commons.lang3.time.DateUtils类
                    Date endTime= DateUtils.parseDate(item.getEndTime(),"yyyy-MM-dd");
                    Date nowTime=new Date();
                    //计算剩余天数
                    int endDays= (int) Math.ceil((endTime.getTime()-nowTime.getTime())/1000/60/60/24);
                    //把剩余天数赋值给当前item对象（数据库中没有该字段，该字段是自己添加的）
                    item.setEndDays(endDays);

                    //测试redis
                    /*boolean isSet=redisService.set(item.getId().toString(), item.toString());
                    System.out.println(isSet);
                    System.out.println("redisItem:"+redisService.get(item.getId().toString()));*/
                } catch (ParseException e) {
                    e.printStackTrace();
                    System.out.println("日期转换失败");
                }
            }
            //把项目信息存放到session中传回showItem
            HttpSession session= getSession(request);
            session.setAttribute("itemList", itemList);
            session.setAttribute("itemListNum", itemList.size());
            System.out.println("session:"+itemList);
        }
        return "showItem/showItem";
    }



    /**
     * 滑动鼠标滚轮查询item
     * @param count
     * @param limit
     * @return
     */
    @RequestMapping("queryItem")
    public String queryItem(String count,String limit,HttpServletRequest request){
        System.out.println("-------进入滑动加载程序--------");
        //把前端传过来的分页信息入参
        Map<String,Object> map=new HashMap<>();
        map.put("count",count);
        map.put("limit",limit);
        List<Item> itemList=itemService.queryItemByPages(map);
        if (itemList!=null){
            //计算剩余时间
            for (Item item:itemList){
                try {
                    //使用org.apache.commons.lang3.time.DateUtils类
                    Date endTime= DateUtils.parseDate(item.getEndTime(),"yyyy-MM-dd");
                    Date nowTime=new Date();
                    //计算剩余天数
                    int endDays= (int) Math.ceil((endTime.getTime()-nowTime.getTime())/1000/60/60/24);
                    //把剩余天数赋值给当前item对象（数据库中没有该字段，该字段是自己添加的）
                    item.setEndDays(endDays);

                    //测试redis
                    /*boolean isSet=redisService.set(item.getId().toString(), item.toString());
                    System.out.println(isSet);
                    System.out.println("redisItem:"+redisService.get(item.getId().toString()));*/
                } catch (ParseException e) {
                    e.printStackTrace();
                    System.out.println("日期转换失败");
                }
            }
            //把项目信息存放到session中传回showItem
            HttpSession session= getSession(request);
            session.setAttribute("itemList", itemList);
            session.setAttribute("itemListNum", itemList.size());
            System.out.println("itemListNum:"+itemList.size());
            System.out.println("session:"+itemList);
        }
        //返回的是item的模版页
        return "showItem/itemTemplate";
    }

    /**
     * 项目详情
     * @param id 项目id
     * @param model
     * @return
     */
    @RequestMapping("showItemDetil")
    public String showItemDetil(Integer id,Model model){
        System.out.println("-------准备跳转到展示项目详情id为:"+id+"的页面--------");
        Item item=itemService.queryById(id);
        //查询此itemId的itemInfo
        ItemInfo itemInfo= itemInfoService.queryByItemId(id);
        model.addAttribute("item", item);
        model.addAttribute("itemInfo", itemInfo);
        System.out.println(item);
        System.out.println(itemInfo);
        return "showItem/showItemDetil";
    }


    /**
     * 发布项目第一步
     * @return
     */
    @RequestMapping("publishItem1")
    public String publishItem1(Model model, ZczyAuditItem zczyAuditItem,HttpServletRequest request){
        System.out.println("--------进入第一步提交-------");
        String sessionId=request.getSession().getId();
        //获取存储的用户信息，并存入审核项目中
        LoginObject loginObject=(LoginObject)redisService.get(sessionId);
        System.out.println("----loginObject:"+loginObject);
        zczyAuditItem.setUserId(loginObject.getUserId());
        zczyAuditItem.setCreateby(loginObject.getPhone());
        zczyAuditItem.setCreateby(loginObject.getLoginName());
        //把审核项目放入redis，限时30分钟，当未发布成功时清除redis缓存的
        System.out.println("------zczyAuditItem:"+zczyAuditItem);
        System.out.println(sessionId);
        //把zczyAuditItem 放入redis中
        //先转为json格式字符串，取出时再反编译为Object
        String zczyAuditItemStr=null;
        try {
            zczyAuditItemStr=OBJECT_MAPPER.writeValueAsString(zczyAuditItem);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        boolean isSet=redisService.set(sessionId+"AuditItem",zczyAuditItemStr,600);
        if (isSet){
            return "publishItem/publishItem2";
        }else {
            //需要添加删除图片
            return "error";
        }
    }

    /**
     * 发布项目第二步
     * @return
     */
    @RequestMapping("publishItem2")
    public String publishItem2(Model model,ZczyAuditItem zczyAuditItem2,HttpServletRequest request){
        String sessionId=request.getSession().getId();
        //取出redis中存储的第一页的数据
        String zczyAuditItemStr=null;
        zczyAuditItemStr= (String) redisService.get(sessionId+"AuditItem");
        ZczyAuditItem zczyAuditItem=null;
        try {
            zczyAuditItem=OBJECT_MAPPER.readValue(zczyAuditItemStr,ZczyAuditItem.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //把第一页和第二页的数据整合
        zczyAuditItem.setTargetAmount(zczyAuditItem2.getTargetAmount());
        zczyAuditItem.setPerMoney(zczyAuditItem2.getPerMoney());
        zczyAuditItem.setContact(zczyAuditItem2.getContact());
        zczyAuditItem.setContactNumber(zczyAuditItem2.getContactNumber());
        zczyAuditItem.setItemreturns(zczyAuditItem2.getItemreturns());
        System.out.println(zczyAuditItem);
        //更新redis中的AuditItem
        //先转为json格式字符串，取出时再反编译为Object
        try {
            zczyAuditItemStr=OBJECT_MAPPER.writeValueAsString(zczyAuditItem);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        boolean isSet=redisService.set(sessionId+"AuditItem",zczyAuditItemStr,600);
        if (isSet){
            //把title传到前台用来展示
            model.addAttribute("title", zczyAuditItem.getTitle());
            //把众筹天数传到前台用来计算众筹应付金额
            model.addAttribute("zcDays", zczyAuditItem.getZcDays());
            return "publishItem/publishItem3";
        }else {
            //需要添加删除图片

            return "error";
        }

    }

    /**
     * 发布项目第三步
     * @return
     */
    @RequestMapping("publishItem3")
    public String publishItem3(String createTime,HttpServletRequest request){
        String sessionId=request.getSession().getId();
        String zczyAuditItemStr=null;
        zczyAuditItemStr= (String) redisService.get(sessionId+"AuditItem");
        ZczyAuditItem zczyAuditItem=null;
        try {
            zczyAuditItem=OBJECT_MAPPER.readValue(zczyAuditItemStr,ZczyAuditItem.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
        zczyAuditItem.setCreatetime(createTime);
        System.out.println("zczyAuditItem:"+zczyAuditItem);
        int flag=zczyAuditItemService.addZczyAuditItem(zczyAuditItem);
        if (flag==1){
            //如果添加成功的话就直接清除redis中存储的信息，释放空间
            redisService.del(sessionId+"AuditItem");
            return "publishItem/publishItemSuccess";
        }else {
            //需要添加删除图片

            return "error";
        }

    }

    /**
     * 图片上传到 FastDFS
     * @param dataURL1 上传 列表页 头图
     * @param dataURL2 上传 详情页 头图
     * @return
     */
    @RequestMapping("upLoadImg")
    @ResponseBody
    public Map upLoadImg(String dataURL1,String dataURL2){
        System.out.println("dataURL1"+dataURL1);
        //判断dataUrl1是否为空，如果不为空就取dataURL1的值，为空取dataURL2的值
        String dataURL=dataURL1!=null?dataURL1:dataURL2;
        Map map=new HashMap();
        if (dataURL!=null){
            //获取解码对象
            Base64.Decoder decoder=Base64.getDecoder();
            //第一次出现“,”的序号
            int num=dataURL.indexOf(",",1);
            //substring用来截取字符串，+1是要截取 "," 后的所有字符串
            dataURL=dataURL.substring(num+1);
            System.out.println(dataURL);
            //解析base64，获取图片字节数据
            byte[] decode = decoder.decode(dataURL);
            try {
                //设置一个文件名
                String fileName = DateUtil.getSystemDateTimeByFormat("yyyyMMddHHmmss")+".jpg";
                //上传图片，把返回的路径保存到fdfsURL（如：group1/M00/00/00/rBUADl7wKe6ATs38AAEVId16QNI015.jpg）
                String fdfsURL = FastDFSClient.uploadFile(decode, fileName);
                //获取配置文件中的域名信息，用来拼接完整图片地址
                String url=LoadProperties.findValue("httpUrl");
                //拼接完整图片地址
                fdfsURL=url+fdfsURL;
                System.out.println(fdfsURL);
                map.put("msg","----上传成功---");
                map.put("url", fdfsURL);
            } catch (Exception e) {
                e.printStackTrace();
                map.put("msg","----上传失败---");
            }
        }
        System.out.println("---------------------");
        System.out.println("dataURL2"+dataURL2);

        return map;
    }

}
